require('date-utils').language("cn");

const log4js = require('log4js');
log4js.configure('./config/log4js.json');
const logger = log4js.getLogger();

console.log = logger.info.bind(logger);
console.debug = logger.debug.bind(logger);
console.trace = logger.trace.bind(logger);
console.warn = logger.warn.bind(logger);
console.error = logger.error.bind(logger);
console.fatal = logger.fatal.bind(logger);
console.info = logger.info.bind(logger);


const Koa = require('koa');
const cors = require('@koa/cors');

const Router = require('koa-router');
const JXData = require('./middleware/JXData');

console.log(`start with redis:${process.env.RedisHost || '127.0.0.1'}`);

const CacheManager = require("./utils/CacheManager");
let cacheManager = new CacheManager({
    db: 10,
    host: process.env.RedisHost || '127.0.0.1',
    password: process.env.RedisPwd || "jxRdsPwd."
});

cacheManager.start(process.env.RedisDB || 10)

const router = new Router();

const app = new Koa();

//设置端口
const port = 8080;

// app.use(koaBody({
//     patchNode: true,
//     json : false,
//     strict:false
// }));


const httpLogger = require('./middleware/log4js');
app.use(httpLogger("http"));
app.use(router.routes());
app.use(router.allowedMethods());


const whitelist = ['http://www.yqfxf.cn']
const corsOptions = {
    origin: function (ctx) {
        if (!whitelist.includes(ctx.header.origin)) {
            return false;
        }
        return '*';
    }
}


//
app.on("error", (err, ctx) => {//捕获异常记录错误日志
    console.error(err);
});
router.get('/', async (ctx, next) => {
    console.log(`${Date.now()}:`, ctx.request.body);
    ctx.body = 'OK';
});

router.post('/', JXData(), async (ctx, next) => {
    let data = ctx.req.JXData;
    console.log(data);

    let now = new Date();
    let date = now.toFormat("YYYYMMDD");
    let time = now.toFormat("HH24MI");
    //写入历史数据
    let key = `data:${data.device}:${date}:${time}`;
    await cacheManager.set(key, JSON.stringify(data));
    //写入当前数据
    await cacheManager.set(`data:${data.device}:current`, JSON.stringify(data));

    await cacheManager.expire(key, 60 * 60 * 24 * 7);

    ctx.body = 'OK';
});
/**
 * 实时数据
 */
router.get('/realtime/:device', cors({ origin: '*' }), async (ctx, next) => {
    let device = ctx.params.device;
    try {
        let data = await cacheManager.get(`data:${device}:current`);
        ctx.body = { status: 1, data };
    }
    catch (e) {
        console.error(e);
        ctx.body = { status: 0, data: [], msg: e.message };
    }
});

/**
 * 实时数据
 */
router.get('/realtime', cors({ origin: '*' }), async (ctx, next) => {
    try {
        let keys = await cacheManager.keys(`data:*:current`);
        let data = [];
        for (let key of keys) {
            data.push(await cacheManager.get(key));
        }
        ctx.body = { status: 1, data };
    }
    catch (e) {
        console.error(e);
        ctx.body = { status: 0, data: [], msg: e.message };
    }
});

/**
 * 每周数据
 */
router.get('/week/:device', cors({ origin: '*' }), async (ctx, next) => {
    let device = ctx.params.device;
    let datas = [];
    let date = new Date();
    try {
        for (let i = 0; i < 7; i++) {
            var data = { date: date.toFormat("YYYY-MM-DD"), detail: {} };
            let keys = await cacheManager.keys(`data:${device}:${date.toFormat("YYYYMMDD")}:*`);
            for (let key of keys) {
                let d = await cacheManager.get(key);
                for (let p in d.detail) {
                    data.detail[p] = (data.detail[p] || 0) + (d.detail[p] || 0);
                }
            }
            for (let p in data.detail) {
                data.detail[p] = ((data.detail[p] || 0) / keys.length).toFixed(1);
            }
            datas.push(data);
            date = date.add({ days: -1 });
        }
        ctx.body = { status: 1, data: datas.reverse() };
    }
    catch (e) {
        console.error(e);
        ctx.body = { status: 0, data: [], msg: e.message };
    }
});

app.listen(port);